package com.ycxy.springsecuritycourse.service.impl;

import com.ycxy.springsecuritycourse.entity.LoginUser;
import com.ycxy.springsecuritycourse.entity.Users;
import com.ycxy.springsecuritycourse.service.LoginService;
import com.ycxy.springsecuritycourse.utils.JwtTokenUtil;
import com.ycxy.springsecuritycourse.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisCache redisCache;

    @Override
    public String login(Users user) throws Exception {

        //进行认证
        Authentication authenticate = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            throw new Exception("认证失败 "+e.getMessage());
        }
        //如果没通过 给出对应提示
        if(Objects.isNull(authenticate)){
            throw new Exception("登录失败");
        }
        //如果认证通过了，以userid生成一个jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String token = jwtTokenUtil.generateToken(loginUser.getUsers());
        //将user的信息传入redis
        redisCache.setCacheObject("login:"+loginUser.getUsers().getId(),loginUser);
        return token;
    }
}
